<template>
  <div>
    <el-main>
      <div class="box">
        <div class="top">
          <el-form
            :inline="true"
            class="demo-form-inline"
            style="float: left"
            size="medium"
          >
            <el-form-item label="监测时间(年-月)：">
              <el-date-picker
                type="month"
                placeholder="选择月"
                style="width: 160px"
              />
            </el-form-item>
            <el-form-item label="节肢动物名称：">
              <el-input
                v-model="queryForm.keyword"
                placeholder="节肢动物名称"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSearch">查询</el-button>
            </el-form-item>
          </el-form>
          <div
            style="
              float: right;
              margin-right: 60px;
              display: flex;
              align-items: center;
            "
          >
            <el-button type="primary" size="medium" @click="handleAddPlant"
              >添加</el-button
            >
            <el-button
              type="danger"
              style="margin-right: 10px"
              :disabled="delIds.length === 0"
              @click="batchDelete"
              >批量删除</el-button
            >
            <el-button @click="openDialog">批量录入数据</el-button>

            <el-dialog
              :visible.sync="dialogVisible"
              title="节肢动物批量录入数据"
              center
              :before-close="handleDialogClose"
              width="80%"
            >
              <!-- 选中文件的input -->
              <div class="dialog-content" style="margin-bottom: 20px">
                <div class="batch-btn-row">
                  <label class="file-upload batch-btn">
                    <input
                      ref="fileInput"
                      type="file"
                      accept=".csv,.xlsx,.xls"
                      @change="handleFileUpload"
                    />
                    选择文件
                  </label>
                  <el-button
                    type="success"
                    size="small"
                    icon="el-icon-download"
                    class="batch-btn"
                    @click="downloadTemplate"
                  >
                    下载模板
                  </el-button>
                  <el-button
                    type="primary"
                    size="small"
                    class="batch-btn"
                    :disabled="
                      isButtonDisabled ||
                      formDataExcel.length === 0 ||
                      errorMessages.length > 0
                    "
                    @click="insertAllDataFromExcel"
                  >
                    {{ buttonText }}
                  </el-button>
                </div>

                <!-- 错误信息提示 -->
              </div>
              <div
                v-if="errorMessages.length > 0"
                class="error-messages"
                style="
                  text-align: center;
                  color: #f56c6c;
                  background-color: #fef0f0;
                  padding: 10px;
                  border-radius: 4px;
                  margin-top: 10px;
                "
              >
                <p
                  v-for="(message, index) in errorMessages"
                  :key="index"
                  style="margin: 5px 0"
                >
                  {{ message }}
                </p>
              </div>
            </el-dialog>
          </div>
        </div>

        <div class="center">
          <el-table
            :data="paginatedData"
            border
            style="width: 100%"
            size="medium"
            :max-height="tableheight"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" show-overflow-tooltip />
            <!-- <el-table-column prop="id" label="序号" width="60px" /> -->
            <el-table-column width="60px" label="序号">
              <template slot-scope="scope">
                <span>{{
                  (currentPage - 1) * pageSize + scope.$index + 1
                }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="wzm" label="中文名" show-overflow-tooltip />

            <el-table-column prop="ldm" label="学名" show-overflow-tooltip />
            <el-table-column
              prop="ldmfull"
              label="学名全称"
              show-overflow-tooltip
            />
            <el-table-column
              prop="shitishuliang"
              label="实体数量"
              width="100"
              show-overflow-tooltip
            />
            <el-table-column
              prop="jd"
              label="经度"
              width="100"
              show-overflow-tooltip
            />
            <el-table-column
              prop="wd"
              label="纬度"
              width="100"
              show-overflow-tooltip
            />
            <el-table-column
              prop="hb"
              label="海拔"
              width="100"
              show-overflow-tooltip
            />
            <el-table-column
              prop="mengshi"
              label="盟市"
              width="120"
              show-overflow-tooltip
            />
            <el-table-column
              prop="qixian"
              label="旗县(区)"
              width="120"
              show-overflow-tooltip
            />
            <el-table-column
              prop="guance"
              label="观测者"
              width="100"
              show-overflow-tooltip
            />
            <el-table-column
              prop="diaochariqi"
              label="调查时间"
              width="150"
              show-overflow-tooltip
              :formatter="formatTimestamp"
            />
            <el-table-column prop="status" label="状态" width="90">
              <template slot-scope="scope">
                <el-tag type="success" size="small">已录入</el-tag>
              </template>
            </el-table-column>

            <el-table-column
              prop="action"
              label="操作"
              width="170"
              align="center"
            >
              <template slot-scope="scope">
                <!-- 操作按钮 -->
                <el-button
                  type="primary"
                  size="mini"
                  @click="xiugai(scope.row)"
                >
                  修改
                </el-button>
                <el-button
                  type="danger"
                  size="mini"
                  @click="deleteItem(scope.row.id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="bottom">
          <el-pagination
            :current-page="currentPage"
            background
            layout="total, prev, pager, next, jumper"
            :total="totalItems"
            :page-size="pageSize"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-main>
    <!-- 页面内容 -->
  </div>
</template>

<script>
import { MessageBox, Message } from "element-ui";
import * as XLSX from "xlsx";
export default {
  // 组件逻辑
  data() {
    return {
      tableheight: 300,
      currentPage: 1, // 当前页码
      pageSize: 9, // 每页显示的数据量
      totalItems: 0, // 总项目数
      dialogVisible: false,
      isButtonDisabled: false, // 初始化按钮可点击状态
      excelData: null,
      buttonText: "录入全部数据",
      formDataExcel: [],
      errorMessages: [],
      queryForm: {
        keyword: "", // 查询关键字
      },
      tableData: [],
      paginatedData: [], // 当前页的数据
      filteredData: [],
      delIds: [],
    };
  },
  computed: {},
  watch: {
    "$store.state.animal.animalData": {
      handler(newValue, oldValue) {
        if (newValue && newValue.length > 0) {
          this.tableData = newValue;
          this.filteredData = newValue.filter(
            (animal) => animal.category === this.$route.meta.category
          );
          this.totalItems = this.filteredData.length;
          this.paginateData();
        } else {
          // 处理为空的情况，比如触发重新获取数据的操作
          this.$store.dispatch("animal/fetchAnimalData");
        }
      },
      immediate: true, // 立即执行一次 handler
    },
  },
  created() {
    const height = window.innerHeight - 200;
    this.tableheight = height;
    // this.fetchData();
    // console.log('有没有值',this.$store.state.animal.animalData);
    // 判断是否已经存在数据
    // if (
    //   !this.$store.state.animal.animalData ||
    //   this.$store.state.animal.animalData.length === 0
    // ) {
    //   // 如果没有数据，调用 fetchData 方法
    //   this.fetchData();
    //   const currentPageCategory = this.$route.meta.category;
    //   console.log("444444", currentPageCategory);
    //   console.log("555555", this.$store.state.animal.animalData);
    // } else {
    // 如果已经有数据，直接使用 Vuex 中的数据
    const currentPageCategory = this.$route.meta.category;
    console.log("3333", currentPageCategory);
    this.tableData = this.$store.state.animal.animalData.filter(
      (animal) => animal.category === currentPageCategory
    );
    this.filteredData = this.$store.state.animal.animalData.filter(
      (animal) => animal.category === currentPageCategory
    );
    this.totalItems = this.tableData.length;
    this.paginateData();
    // }
  },
  methods: {
    fetchData() {
      this.$store.dispatch("animal/fetchAnimalData");
    },
    // fetchData() {
    //   // 调用 user.js 中的 getData 方法
    //   this.$api
    //     .getAnimalData()
    //     .then((response) => {
    //       if (response.data.code == 906) {
    //         // return  alert('token已过期')
    //         this.$router.push(`/login`);
    //       }

    //       console.log(222);
    //       console.log("植物数据", response);
    //       this.tableData = response.data.data;
    //       this.filteredData = response.data.data;
    //       this.totalItems = this.tableData.length;
    //       this.paginateData();
    //     })
    //     .catch((error) => {
    //       // 处理错误
    //       console.error(error);
    //     });
    // },
    // 切换分页
    paginateData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.paginatedData = this.filteredData.slice(start, end);
    },
    handleCurrentChange(val) {
      // 当用户切换分页时触发
      this.currentPage = val;
      this.paginateData();
    },
    onSearch() {
      console.log("查询");
      const keyword = this.queryForm.keyword.trim().toLocaleLowerCase();
      console.log("遍历的数据", this.tableData);

      this.filteredData = this.tableData.filter((item) => {
        const itemWzm = String(item.wzm).toLocaleLowerCase();
        const itemLdm = String(item.ldm).toLocaleLowerCase();

        // 判断条件：要么和关键字一样，要么包含全部的关键字
        return (
          itemWzm === keyword ||
          itemLdm === keyword ||
          keyword.split(/\s+/).every((kw) => itemWzm.includes(kw)) ||
          keyword.split(/\s+/).every((kw) => itemLdm.includes(kw))
        );
      });
      console.log(this.filteredData);

      this.totalItems = this.filteredData.length;
      this.paginateData();
    },
    // 新增
    handleAddPlant() {
      console.log("点击了新增按钮");
      this.$router.push({ name: "insect-add" });
    },
    // 修改
    xiugai(data) {
      console.log("777", data);
      // return
      this.$router.push({
        name: "insect-add",
        query: { data: JSON.stringify(data) },
      });
    },
    handleSelectionChange(val) {
      this.delIds = val;
    },
    deleteItem(id) {
      console.log("删除id", id);
      this.delIds.push(id);
      try {
        MessageBox.confirm("确定要删除吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            // 用户点击了确定按钮
            console.log("用户点击了确定按钮");
            this.$api
              .delPlantData(this.delIds)
              .then((response) => {
                // 处理接口返回的数据或其他逻辑

                // 处理删除成功的情况
                console.log("删除成功", response.data);
                this.$message({
                  message: "删除成功",
                  type: "success",
                });
                // 在前端移除已删除的项
                this.tableData = this.tableData.filter(
                  (item) => item.id !== id
                );
                this.totalItems--; // 减少总项目数
                this.paginateData(); // 更新分页后的数据
                // this.fetchData()
                this.delIds = [];
              })
              .catch((error) => {
                // 处理失败的情况
                console.error("失败:", error);
              });
          })
          .catch(() => {
            // 用户点击了取消按钮
            console.log("用户点击了取消按钮");
            this.delIds = [];
          });
      } catch (error) {
        // 处理删除失败的情况
        console.error("删除失败", error);
      }
    },
    handleDialogClose(done) {
      // 清空相关数据
      // // 调用 done() 完成关闭
      done();
    },
    // 录入全部数据
    handleFileUpload(event) {
      this.errorMessages = []; // 清空之前的错误信息
      // 获取上传的Excel文件
      const file = event.target.files[0];
      // 清除输入值以确保即使选择相同的文件，onload 事件仍然会触发
      event.target.value = null;
      // 使用xlsx读取Excel文件
      const reader = new FileReader();

      reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: "array" });

        // 获取第一个工作表
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];

        // 将Excel数据转为JSON格式
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

        if (jsonData.length < 2) {
          this.errorMessages = ["文件格式错误，至少需要表头行和数据行"];
          this.isButtonDisabled = true;
          return;
        }

        // 获取表头
        const headers = jsonData[0].map((header) =>
          header ? header.toString().trim() : ""
        );

        // 添加调试信息
        console.log("解析到的表头:", headers);

        // 字段映射关系（节肢动物包含学名全称）
        const fieldMapping = {
          中文名: "wzm",
          学名: "ldm",
          学名全称: "ldmfull",
          实体数量: "shitishuliang",
          痕迹种类及数量: "henjishuliang",
          经度: "jd",
          纬度: "wd",
          海拔: "hb",
          坡度: "podu",
          坡位: "powei",
          坡向: "poxiang",
          栖息地类型: "qixi",
          调查日期: "diaochariqi_temp",
          发现时间: "faxianshijian_temp",
          栖息地干扰: "qixiganrao",
          保护等级: "protectlevel",
          发现地址: "location",
          盟市: "mengshi",
          旗县: "qixian",
          数据来源: "source",
          观测者: "guance",
          照片编号: "zpbh",
          生境照片编号: "sjzpbh",
          特征描述: "tezhengmiaoshu",
          分布多度描述: "fenbuduodumiaoshu",
        };

        // 验证必需字段 - 使用更宽松的匹配
        const requiredFields = ["中文名", "学名", "经度", "纬度"];
        const missingFields = [];

        requiredFields.forEach((requiredField) => {
          const found = headers.some((header) => {
            // 精确匹配
            if (header === requiredField) return true;
            // 去除空格后匹配
            if (header.trim() === requiredField) return true;
            // 包含匹配（处理可能的变体）
            if (
              header.includes(requiredField) ||
              requiredField.includes(header)
            ) {
              return true;
            }
            return false;
          });

          if (!found) {
            missingFields.push(requiredField);
          }
        });

        if (missingFields.length > 0) {
          this.errorMessages = [
            `缺少必需字段: ${missingFields.join(", ")}`,
            `当前表头: ${headers.join(", ")}`,
          ];
          this.isButtonDisabled = true;
          return;
        }

        const formDataArray = [];
        const errors = [];

        // 解析数据行
        for (let i = 1; i < jsonData.length; i++) {
          const row = jsonData[i];
          const rowObject = {};

          // 映射字段
          headers.forEach((header, index) => {
            const fieldName = fieldMapping[header] || header;
            let value = row[index] || "";

            // 数据类型转换
            if (
              fieldName === "shitishuliang" ||
              fieldName === "henjishuliang" ||
              fieldName === "hb" ||
              fieldName === "podu"
            ) {
              value = value ? parseInt(value) || 0 : 0;
            } else if (fieldName === "jd" || fieldName === "wd") {
              value = value ? parseFloat(value) || 0 : 0;
            } else if (
              fieldName === "diaochariqi_temp" ||
              fieldName === "faxianshijian_temp"
            ) {
              if (value) {
                const date = new Date(value);
                value = isNaN(date.getTime()) ? null : date;
              } else {
                value = null;
              }
            } else if (typeof value === "string") {
              // 对字符串类型的值也进行trim处理
              value = value.trim();
            }

            rowObject[fieldName] = value;
          });

          // 合并调查日期和发现时间
          if (rowObject.diaochariqi_temp || rowObject.faxianshijian_temp) {
            let combinedDateTime = null;

            if (rowObject.diaochariqi_temp && rowObject.faxianshijian_temp) {
              // 如果两个都有，合并日期和时间
              const surveyDate = new Date(rowObject.diaochariqi_temp);
              const discoveryTime = new Date(rowObject.faxianshijian_temp);

              // 创建新的Date对象，使用调查日期的年月日，发现时间的时分秒
              const combinedDate = new Date(
                surveyDate.getFullYear(),
                surveyDate.getMonth(),
                surveyDate.getDate(),
                discoveryTime.getHours(),
                discoveryTime.getMinutes(),
                discoveryTime.getSeconds()
              );

              // 转换为ISO格式字符串
              combinedDateTime = combinedDate.toISOString();
            } else if (rowObject.diaochariqi_temp) {
              // 只有调查日期，转换为ISO格式
              const date = new Date(rowObject.diaochariqi_temp);
              combinedDateTime = date.toISOString();
            } else if (rowObject.faxianshijian_temp) {
              // 只有发现时间，转换为ISO格式
              const date = new Date(rowObject.faxianshijian_temp);
              combinedDateTime = date.toISOString();
            }

            rowObject.diaochariqi = combinedDateTime;
          } else {
            rowObject.diaochariqi = null;
          }

          // 删除临时字段
          delete rowObject.diaochariqi_temp;
          delete rowObject.faxianshijian_temp;

          // 添加动物类别字段
          rowObject.category = "04"; // 节肢动物标识

          // 验证数据
          if (!rowObject.wzm || !rowObject.ldm) {
            errors.push(`第${i + 1}行: 中文名和学名不能为空`);
            continue;
          }

          if (!rowObject.jd || !rowObject.wd) {
            errors.push(`第${i + 1}行: 经度和纬度不能为空`);
            continue;
          }

          formDataArray.push(rowObject);
        }

        if (errors.length > 0) {
          this.errorMessages = errors.slice(0, 10); // 只显示前10个错误
          if (errors.length > 10) {
            this.errorMessages.push(`...还有${errors.length - 10}个错误`);
          }
        }

        this.formDataExcel = formDataArray;
        this.isButtonDisabled = formDataArray.length === 0;

        if (formDataArray.length > 0) {
          this.errorMessages = [];
          this.buttonText = `录入全部数据 (${formDataArray.length}条)`;
        }

        console.log("解析后的数据:", this.formDataExcel);
      };

      reader.readAsArrayBuffer(file);
    },
    insertData() {
      // 执行数据插入的逻辑，使用 this.formDataExcel
      // 清空相关数据，关闭对话框等操作
      if (this.formDataExcel.length > 0) {
        // 发送请求到后端，提交数据
        this.$api
          .addPantData(this.formDataExcel)
          .then((response) => {
            // 处理成功的情况
            console.log(response);
            this.$message.success("数据提交成功");
            this.fetchData(); // 刷新数据
            this.handleDialogClose();
          })
          .catch((error) => {
            // 处理失败的情况
            console.error("数据提交失败:", error);
            this.$message.error("数据提交失败");
          });
      }
    },
    openDialog() {
      this.dialogVisible = true;
    },
    formatTimestamp(row, column, cellValue) {
      // 使用 JavaScript 内建的 Date 对象来格式化时间戳
      const date = new Date(cellValue);
      return date.toLocaleString(); // 您可以根据需要调整日期时间格式
    },
    batchDelete() {
      if (this.delIds.length === 0) {
        // 如果没有选中项目，不执行删除操作
        return;
      }

      MessageBox.confirm("确定要批量删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 用户点击了确定按钮
          const selectedIds = this.delIds.map((item) => item.id);
          console.log(selectedIds);
          // return
          // const idsString = selectedIds.join(',')
          // console.log('idsString', idsString)
          this.$api
            .delPlantData(selectedIds)
            .then((response) => {
              // 处理接口返回的数据或其他逻辑
              // 处理删除成功的情况
              console.log("批量删除成功", response.data);
              this.$message({
                message: "删除成功",
                type: "success",
              });
              // // 在前端移除已删除的项
              // this.tableData = this.tableData.filter(
              //   (item) => !selectedIds.includes(item.id)
              // )
              // this.totalItems -= selectedIds.length // 减少总项目数
              // this.paginateData() // 更新分页后的数据
              this.$store.dispatch("animal/fetchAnimalData");
              this.delIds = []; // 清空用户选择的项目
            })
            .catch((error) => {
              // 处理失败的情况
              console.error("批量删除失败:", error);
            });
        })
        .catch(() => {
          // 用户点击了取消按钮
          console.log("用户点击了取消按钮");
        });
    },
    downloadTemplate() {
      // 使用完整的URL路径
      const baseUrl = window.location.origin;
      const link = document.createElement("a");
      link.href = `${baseUrl}/insect-template.xlsx`;
      link.download = "节肢动物调查数据模板.xlsx";
      link.style.display = "none";

      // 添加到页面并触发下载
      document.body.appendChild(link);
      link.click();

      // 清理DOM
      document.body.removeChild(link);

      // 显示成功提示
      Message({
        message: "模板下载成功",
        type: "success",
        duration: 3000,
      });
    },
    insertAllDataFromExcel() {
      if (this.errorMessages.length > 0) {
        // 显示错误信息
        Message({
          message: this.errorMessages.join("; "),
          type: "error",
          duration: 5000,
        });
        return;
      }

      if (this.formDataExcel.length === 0) {
        Message({
          message: "请先选择Excel文件",
          type: "warning",
          duration: 3000,
        });
        return;
      }

      this.isButtonDisabled = true;
      this.buttonText = "录入中...";
      console.log("录入全部数据:", this.formDataExcel);

      // 使用surveySample接口提交数据
      this.$api
        .addPantData(this.formDataExcel)
        .then((response) => {
          console.log("response", response);
          if (response.data.code === 0) {
            Message({
              message: "录入成功",
              type: "success",
              duration: 3000,
            });
            this.formDataExcel = [];
            this.errorMessages = []; // 清空错误信息
            this.dialogVisible = false; // 关闭对话框
            // 录入成功后重新获取数据
            this.fetchData();
          } else {
            Message({
              message: response.data.message || "录入失败",
              type: "error",
              duration: 3000,
            });
          }
        })
        .catch((error) => {
          console.log(error);
          Message({
            message: "录入失败，请检查数据格式",
            type: "error",
            duration: 3000,
          });
          this.buttonText = `录入全部数据 (${this.formDataExcel.length}条)`;
          this.isButtonDisabled = false;
        });
    },
  },
};
</script>

<style scoped>
.el-main {
  color: #333;
  box-sizing: border-box;
}
/* .box {
  padding: 15px;
  background: rgb(255, 255, 255);
  height: 700px;
  position: relative;
  overflow-y: auto;
} */
.top {
  background-color: rgb(232, 232, 232);
  border-radius: 2px;
  padding-left: 20px;
  padding-top: 8px;
  padding-bottom: 7px;
  overflow: hidden;
}
.center {
  /* height: 400px; */
}
.el-form-item {
  margin-bottom: 2px;
  vertical-align: top;
  margin-right: 16px;
}
.bottom {
  text-align: right;
}

.file-upload {
  margin-right: 20px;
}

.file-upload input {
  display: none;
}

.file-upload {
  display: inline-block;
  cursor: pointer;
  padding: 10px 20px;
  background-color: #3498db;
  color: #fff;
  border-radius: 5px;
}

.dialog-content {
  display: flex;
  justify-content: center;
  height: 100%;
}

.batch-btn-row {
  display: flex;
  gap: 16px;
  align-items: center;
  justify-content: center;
  margin-bottom: 15px;
}

.batch-btn {
  margin: 0 !important;
  min-width: 90px;
}

.file-upload.batch-btn {
  padding: 7px 18px;
  font-size: 14px;
  background-color: #409eff;
  color: #fff;
  border-radius: 4px;
  border: none;
  transition: background 0.2s;
}

.file-upload.batch-btn:hover {
  background-color: #66b1ff;
}

.error-messages {
  background-color: #fef0f0;
  border: 1px solid #fbc4c4;
  border-radius: 4px;
  padding: 10px;
  margin-top: 10px;
}
</style>
